import axios, { AxiosInstance } from 'axios'
import type { CYRequestConfig, CYRequestInterceptors } from './type'

import { ElLoading } from 'element-plus'
import { ILoadingInstance } from 'element-plus/lib/el-loading/src/loading.type'

const DEAFULT_LOADING = true

class CYRequest {
  instence: AxiosInstance
  interceptors?: CYRequestInterceptors
  loading?: ILoadingInstance
  showLoading?: boolean

  constructor(config: CYRequestConfig) {
    // 创建axios实例
    this.instence = axios.create(config)

    // 保存基本信息
    this.interceptors = config.interceptors
    this.showLoading = config.showLoading ?? DEAFULT_LOADING

    // 使用拦截器
    // 1.添加每个实例特有的拦截器
    this.instence.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )
    this.instence.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    )

    // 2.添加所有实例通有的拦截器
    this.instence.interceptors.request.use(
      (config) => {
        // console.log('所有实例通有的请求拦截器')

        // 设置loading加载动画
        if (this.showLoading === true) {
          this.loading = ElLoading.service({
            lock: true,
            text: '正在加载......',
            background: 'rgba(0,0,0,0.5)'
          })
        }
        return config
      },
      (error) => {
        return error
      }
    )
    this.instence.interceptors.response.use(
      (res) => {
        // console.log('所有实例通有的响应拦截器')
        // 清除loading
        // setTimeout(() => {
        //   this.loading?.close()
        // }, 100)
        this.loading?.close()

        const data = res.data
        if (data.returnCode === '-1001') {
          console.log('请求失败，请重试')
        } else {
          return data
        }
      },
      (error) => {
        return error
      }
    )
  }

  // 封装请求
  request<T>(config: CYRequestConfig): Promise<T> {
    return new Promise((resolve, reject) => {
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors?.requestInterceptor(config)
      }

      if (config.showLoading === false) {
        this.showLoading = config.showLoading
      }

      this.instence
        .request<any, T>(config)
        .then((res) => {
          if (config.interceptors?.responseInterceptor) {
            res = config.interceptors?.responseInterceptor(res)
          }
          // 将showLoading设置成默认值，这样不会影响下一个请求
          this.showLoading = DEAFULT_LOADING
          // 返回数据
          resolve(res)
        })
        .catch((error) => {
          // 将showLoading设置成默认值，这样不会影响下一个请求
          this.showLoading = DEAFULT_LOADING
          reject(error)
        })
    })
  }

  get<T>(config: CYRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'GET' })
  }

  post<T>(config: CYRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'POST' })
  }

  delete<T>(config: CYRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'DELETE' })
  }

  put<T>(config: CYRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'PUT' })
  }
}

export default CYRequest
